import { createStore, createLogger } from 'vuex'
import { isPlainObject } from '../assets/utils'
import api from '../api'

const env = process.env.NODE_ENV
const store = createStore({
    state: {
        info: null,
        storyList: null
    },
    mutations: {
        setInfo(state, payload) {
            if (!isPlainObject(payload)) return;
            state.info = payload;
        },
        setStoryList(state, payload) {
            if (!Array.isArray(payload)) return;
            state.storyList = payload;
        },
        removeStoryList(state, id) {
            if (!state.storyList) return;
            state.storyList = state.storyList.filter(item => +item.id !== +id);
        }
    },
    actions: {
        async setInfoAsync({ commit }) {
            let { code, data } = await api.queryUserInfo();
            if (+code !== 0) return Promise.reject(null);
            commit('setInfo', data);
            return data;
        },
        async setStoryListAsync({ commit }) {
            let { code, data } = await api.storeList();
            if (+code !== 0) return Promise.reject(null);
            commit('setStoryList', data);
            return data;
        }
    },
    plugins: env !== 'production' ? [createLogger()] : []
})
export default store